using System;
using System.Collections;
using System.Globalization;
using System.IO;

using System.Xml;

namespace GURUCORE.Framework.Core.Util.Localization
{
	/// <summary>
	///		ResourceManager class used to access localized content in XML files
	/// </summary>
	public sealed class ResourceManager
	{
		public const string GLOBAL_CACHE_KEY = "ResourceManager";
		
		private ResourceManager()
		{
		}

		/// <summary>
		/// get a localized string base on key and section
		/// </summary>
		/// <param name="p_sSection"></param>
		/// <param name="p_sKey"></param>
		/// <returns></returns>
		public static string GetString(string p_sSection, string p_sKey) 
		{
			string sLocale = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
			Hashtable htRes = (Hashtable)GApplication.GetInstance().GetSharedObject(GLOBAL_CACHE_KEY + "#" + sLocale);
			if (htRes.ContainsKey(p_sSection + "#" + p_sKey))
			{
				return htRes[p_sSection + "#" + p_sKey].ToString();
			}
			else
			{
				return string.Empty;
			}
		}

        public static string GetString(Exception p_ex, string p_sKey)
        {
            // TODO: GURUCORE need to implement
            return p_sKey;
        }

        public static string GetString(object p_1, object p_2, string p_sKey)
        {
            // TODO: GURUCORE need to implement
            return p_sKey;
        }

        public static string GetString(int p_Code, string p_sKey)
        {
            // TODO: GURUCORE need to implement
            return p_sKey;
        }

        // TODO: Export to config file base
        const string LANGUAGE_DIR = "Language/";

		/// <summary>
		/// load localized resources for given locale
		/// </summary>
		/// <param name="p_sLocale"></param>
		/// <param name="p_sAppRootDir"></param>
		/// <returns></returns>
		public static Hashtable LoadResource(string p_sLocale, string p_sAppRootDir) 
		{			
			string file = p_sAppRootDir + LANGUAGE_DIR + p_sLocale + "/language.xml";

			try
			{
				Hashtable htResource = new Hashtable();

				XmlDocument xml = new XmlDocument();
				xml.Load(file);
				foreach (XmlNode n in xml.SelectSingleNode("Language"))
				{
					if (n.NodeType != XmlNodeType.Comment)
					{
						foreach (XmlNode oItemNode in n.SelectNodes("Item"))
						{
							if (oItemNode.NodeType != XmlNodeType.Comment)
							{
								htResource[n.Attributes["name"].Value + "#" + oItemNode.Attributes["name"].Value] = oItemNode.InnerText;
							}
						}
					}
				}

				return htResource;
			}
			catch // (Exception ex)
			{
				return null;
			}
		}      

	}   // end class
}   // end namespace
